<template>
  <el-dialog title="批量更新" v-model="open" width="800px" append-to-body>
    <el-form ref="roleRef" :inline="false" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="授权码" prop="key">
        <span>{{ keys }}</span>
      </el-form-item>

      <el-form-item label="token" prop="token">
        <el-input v-model.trim="form.token" placeholder="请输入token" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定 </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { updateBatchApi } from "@/api/base/index.js";

const emit = defineEmits(["refresh"]);
const { proxy } = getCurrentInstance();

const open = ref(false);
const loading = ref(false);
const list = ref([]);
const form = ref({
  token: "",
});

const rules = {
  token: [{ required: true, message: "token不能为空", trigger: "blur" }],
};

const keys = computed(() => list.value.map((v) => v.key).join(", "));

const init = (rows) => {
  open.value = true;
  list.value = toRaw(rows);
};

const cancel = () => {
  open.value = false;
};

const submitForm = async () => {
  proxy.$refs["roleRef"].validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await updateBatchApi(
          list.value.map((v) => {
            return {
              ...v,
              guildId: form.value.token,
            };
          })
        );
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        emit("refresh");
      } catch (error) {
        //
      }
      loading.value = false;
    }
  });
};

defineExpose({
  init,
});
</script>
